﻿using System.Collections.Generic;
using System.Reflection;
using Microsoft.VisualStudio.Modeling;
using Microsoft.VisualStudio.Modeling.Shell;
using Microsoft.Win32;
using System;
using System.Globalization;

namespace DSLFactory.VSCTDesigner
{
    static class ShellHelper
    {
        private static string _sdkInstallationDir;
        private const string sdkVersion = "9.0";

        public static string GetModelFileName(Store store)
        {
            ModelingDocStore docStore = (ModelingDocStore)store.PropertyBag[ModelingDocStore.ModelingDocStoreKey];
            PropertyInfo pi = docStore.GetType().GetProperty("ModelingDocuments", BindingFlags.NonPublic | BindingFlags.Instance);
            var docdatas = (IList<ModelingDocData>)pi.GetValue(docStore, null);
            return docdatas[0].FileName;
        }

        public static string GetSDKInstallationPath()
        {
            if( string.IsNullOrEmpty(_sdkInstallationDir) )
            {
                _sdkInstallationDir = Environment.GetEnvironmentVariable("VsSDKInstall");
                if( !string.IsNullOrEmpty(_sdkInstallationDir) )
                {
                    return _sdkInstallationDir;
                }

                string name = string.Format(CultureInfo.InvariantCulture, @"{0}\{1}", new object[] { @"Software\Microsoft\VisualStudio\VSIP", sdkVersion });
                using( RegistryKey key = Registry.LocalMachine.OpenSubKey(name) )
                {
                    if( key != null )
                    {
                        _sdkInstallationDir = key.GetValue("InstallDir") as string;
                    }
                }
            }
            return _sdkInstallationDir;
        }

        public static string GetSDKToolsPath()
        {
            string environmentVariable = Environment.GetEnvironmentVariable("VsSDKToolsPath");
            if( !string.IsNullOrEmpty(environmentVariable) )
            {
                return environmentVariable;
            }
            string sDKInstallationPath = GetSDKInstallationPath();
            if( string.IsNullOrEmpty(sDKInstallationPath) )
            {
                return String.Empty;
            }
            return System.IO.Path.Combine(sDKInstallationPath, @"VisualStudioIntegration\Tools\bin");
        }
    }
}
